package com.example.treehole.ui.page.login

import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.component.isValidEmail
import com.example.treehole.ui.component.showLoginSnackbar
import com.example.treehole.ui.model.UserViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class LoginViewModel : ViewModel() {
    private val _inputEmail = MutableStateFlow<String>("")
    val inputEmail: StateFlow<String> = _inputEmail

    fun updateInputEmail(email: String) {
        _inputEmail.value = email
    }

    suspend fun registerUser(
        password: String,
        verifyCode: String
    ): Boolean {
        if (isValidEmail(inputEmail.value)) {
            val res = DataRepository.registerUser(inputEmail.value, password, verifyCode)
            res?.let { return true } ?: return false
        } else {
            showLoginSnackbar("请输入有效邮箱")
            return false
        }
    }

    suspend fun modifyPassword(
        password: String,
        verifyCode: String
    ): Boolean {
        if (isValidEmail(inputEmail.value)) {
            val res = DataRepository.modifyPassword(inputEmail.value, password, verifyCode)
            return res
        } else {
            showLoginSnackbar("请输入有效邮箱")
            return false
        }
    }

    suspend fun loginByPassword(
        password: String,
        userViewModel: UserViewModel
    ): Boolean {
        if (isValidEmail(inputEmail.value)) {
            val res = DataRepository.loginByPassword(inputEmail.value, password)
            res?.let {
                userViewModel.login(
                    it.userId,
                    it.jwt
                )
                return true
            } ?: return false
        } else {
            showLoginSnackbar("请输入有效邮箱")
            return false
        }
    }

    suspend fun loginByVerify(
        verifyCode: String,
        userViewModel: UserViewModel
    ): Boolean {
        if (isValidEmail(inputEmail.value)) {
            val res = DataRepository.loginByVerify(inputEmail.value, verifyCode)
            res?.let {
                userViewModel.login(
                    it.userId,
                    it.jwt
                )
                return true
            } ?: return false
        } else {
            showLoginSnackbar("请输入有效邮箱")
            return false
        }
    }

}